package com.cp.service;

import com.cp.repository.AdjudgmentWord;
import com.cp.repository.ClassRelation;
import com.cp.repository.CodeSemanticChunk;
import com.cp.repository.Config;
import com.cp.utils.JSONUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class FormatJSON {

	@Autowired
	Config config;

	@Autowired
	AdjudgmentWordService adjudgmentWordService;

	public String formatInputSuggest(List<CodeSemanticChunk> codeSemanticChunkList, String keyWord) {
		String out = "";
		if(!codeSemanticChunkList.isEmpty()) {
		    out += "<ul class=\"typeahead dropdown-menu\" role=\"listbox\" style=\"top: 34px; left: 0px; display: block; max-height: 200px; max-width: 600px; overflow: scroll;\">";
            for(CodeSemanticChunk csc : codeSemanticChunkList) {
                out += "<li>" +
                        "<a class=\"dropdown-item\" href=\"javascript:selectCodeSemanticChunk("+csc.getId()+", '"+csc.getConviction().getContent()+" -- "+ csc.getContent()+"', "+csc.getConviction().getId()+")\" role=\"option\"> "+csc.getConviction().getContent()+" -- "+ csc.getContent().replace(keyWord, "<span class='redTxt'>"+keyWord+"</span>") +" </a>" +
                        "</li>";
            }
		    out += "</ul>";
        }
		return out;
	}

	/**
	 * 组装语义场景框架树形结构json
	 * @param codeSemanticChunk
	 * @param codeSemanticChunkList
	 * @return
	 */
	public String formatCodeSemanticChunk(CodeSemanticChunk codeSemanticChunk, List<CodeSemanticChunk> codeSemanticChunkList, List<ClassRelation> classRelationList) {
		String jsonStr = config.getJson();
		ObjectMapper mapper = new ObjectMapper();
		try {
			Map<String, Object> map = JSONUtils.json2map(jsonStr);
			LinkedHashMap<String, Object> dataMap = (LinkedHashMap)map.get("data");
            dataMap.put("topic", codeSemanticChunk.getConviction().getContent());
			List childrenList = (List)dataMap.get("children");
            for(int i = 0; i < childrenList.size(); i++) {
	            LinkedHashMap<String, Object> o = (LinkedHashMap)childrenList.get(i);
	            String id = (String)o.get("id");
	            List myChildrenList = null;
	            for(CodeSemanticChunk csc : codeSemanticChunkList) {
		            Integer classRelationId = csc.getClassRelation().getId();
		            if(id.split("_").length==2 && ("codeSemanticChunk_"+classRelationId).equals(id)) {
			            myChildrenList = (List)o.get("children");
			            addChildren(myChildrenList, "codeSemanticChunk_1_"+i, csc.getContent(), codeSemanticChunk.getContent(), "", "");
		            } else {//遍历children子节点
						List subChildrenList = (List)o.get("children");
						for(int j = 0; j < subChildrenList.size(); j++) {
							LinkedHashMap<String, Object> subChildrenMap = (LinkedHashMap)subChildrenList.get(j);
							if(("codeSemanticChunk_"+classRelationId).equals(subChildrenMap.get("id"))) {
								myChildrenList = (List)subChildrenMap.get("children");
								addChildren(myChildrenList, "codeSemanticChunk_2_"+csc.getId()+"_"+j, csc.getContent(), codeSemanticChunk.getContent(), "", "");
							}
						}
		            }
	            }
            }
            jsonStr = mapper.writeValueAsString(map);
        } catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}

	private void addChildren(List list, String id, String topic, String keyWord, String backgroundColor, String direction) {
		Map<String, String> map = new LinkedHashMap<>();
		map.put("id", id);
		map.put("topic", topic);
		if(!"".equals(keyWord)) {
			if (topic.equals(keyWord)) {
				map.put("background-color", "red");
			} else {
				map.put("background-color", "gray");
			}
		}
		if(!"".equals(backgroundColor)){
			map.put("background-color", backgroundColor);
		}
		if(!"".equals(direction)){
			map.put("direction", direction);
		}
		list.add(map);
	}

	public String yycc(CodeSemanticChunk codeSemanticChunk) {
		String jsonStr = "{\"meta\":{\"name\":\"cp\",\"author\":\"\",\"version\":\"\"},\"format\":\"node_tree\",\"data\":{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"语义层次\",\"background-color\":\"lightsalmon\",\"foreground-color\":\"white\",\"children\":[{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\""+codeSemanticChunk.getConviction().getContent()+"\",\"children\":[{";
		String classRelation = codeSemanticChunk.getClassRelation().getContent();
		for(String children : classRelation.split("\\-")){
			jsonStr += addChildrenStart(children);
		}
		jsonStr += "\"background-color\": \"red\"," + addChildrenStart(codeSemanticChunk.getContent())+"}]";
		for(String children : classRelation.split("\\-")){
			jsonStr += "}]";
		}

		jsonStr += "}]}]}}";
		jsonStr = jsonStr.replace(",\"children\":[{}]", "");
		return jsonStr;
	}



	/**
	 * 5, 3 ,17, 9, 22, 6, 10, 4
	 * @param list
	 * @return
	 */
	public String formatAdjudgmentWordJson(List<AdjudgmentWord> list, String title){
		String jsonStr = "";
		String jsonStart = "{\"meta\":{\"name\":\"cp\",\"author\":\"\",\"version\":\"\"},\"format\":\"node_tree\",\"data\":{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\""+title+"\",\"background-color\":\"lightsalmon\",\"foreground-color\":\"white\",\"children\":[";
		String subJson3 = "[{";
		String subJson4 = "[{";
		String subJson5 = "[{";
		String subJson6 = "[{";
		String subJson9 = "[{";
		String subJson10 = "[{";
		String subJson17 = "[{";
		String subJson22 = "[{";
		for(AdjudgmentWord adjudgmentWord : list) {
			if(adjudgmentWord.getClassRelation().getId() == 3){
				subJson3 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 4){
				subJson4 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 5){
				subJson5 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 6){
				subJson6 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 9){
				subJson9 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 10){
				subJson10 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 17){
				subJson17 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 22){
				subJson22 += addChildrenStart(adjudgmentWord);
			}
		}
		for(AdjudgmentWord adjudgmentWord : list) {
			if(adjudgmentWord.getClassRelation().getId() == 3){
				subJson3 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 4){
				subJson4 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 5){
				subJson5 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 6){
				subJson6 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 9){
				subJson9 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 10){
				subJson10 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 17){
				subJson17 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 22){
				subJson22 += "}]";
			}
		}
		if(subJson3.replaceAll("[\\[\\{\\}\\]]", "").length()!=0){
			subJson3 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"A行为内容\",\"children\":" + subJson3 + "}]}";
		} else {
			subJson3 = "";
		}
		if(subJson4.replaceAll("[\\[\\{\\}\\]]", "").length()!=0){
			subJson4 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"B行为情节\",\"children\":" + subJson4 + "}]}";
		} else {
			subJson4 = "";
		}
		if(subJson5.replaceAll("[\\[\\{\\}\\]]", "").length()!=0){
			subJson5 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"C方式方法手段\",\"children\":" + subJson5 + "}]}";
		} else {
			subJson5 = "";
		}
		if(subJson6.replaceAll("[\\[\\{\\}\\]]", "").length()!=0){
			subJson6 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"D数量数额\",\"children\":" + subJson6 + "}]}";
		} else {
			subJson6 = "";
		}
		//jsonPart3取代subJson3-6
		String jsonPart3 = "";
		if((subJson3+subJson4+subJson5+subJson6).replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			jsonPart3 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"三、行为\",\"children\":[" + subJson3 + subJson4 + subJson5 + subJson6 +"]}";
		}

		if(subJson9.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson9 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"六、行为后果\",\"children\":"+ subJson9 + "}]}";
		}else {
			subJson9 = "";
		}
		if(subJson10.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson10 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"七、主观心态\",\"children\":[{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"A故意 过失\",\"children\":"+ subJson10 + "}]}]}";
		} else {
			subJson10 = "";
		}
		if(subJson17.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson17 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"九、刑罚\",\"children\":[{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"D量刑情节\",\"children\":"+ subJson17 + "}]}]}";
		} else {
			subJson17 = "";
		}
		if(subJson22.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson22 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"十、其他\",\"children\":[{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"A基础术语\",\"children\":"+ subJson22 + "}]}]}";
		} else {
			subJson22 = "";
		}

		jsonStr = jsonStart + jsonPart3 + subJson9 + subJson10 + subJson17 + subJson22;
		jsonStr = jsonStr.replace("{}", "").replace("}{", "},{");
		return jsonStr + "]}}";


//		String jsonStr = config.adjudgmentWordJson;
//		ObjectMapper mapper = new ObjectMapper();
//		try {
//			Map<String, Object> map = JSONUtils.json2map(jsonStr);
//			LinkedHashMap<String, Object> dataMap = (LinkedHashMap)map.get("data");
//			if(!list.isEmpty()){
//				dataMap.put("topic", list.get(0).getAdjugmentRelationWord().getContent());
//			}
//			List childrenList = (List)dataMap.get("children");
//			int i = list.size();
//
//			for(AdjudgmentWord adjudgmentWord : list) {
//				if(i >= 6) {
//					if(i%2==1) {
//						addChildren(childrenList, adjudgmentWord.getContent()+i, adjudgmentWord.getContent(), "", "", "left");
//					} else {
//						addChildren(childrenList, adjudgmentWord.getContent()+i, adjudgmentWord.getContent(), "", "", "right");
//					}
//				} else {
//					addChildren(childrenList, adjudgmentWord.getContent()+i, adjudgmentWord.getContent(), "", "", "right");
//				}
//				i--;
//			}
//			jsonStr = mapper.writeValueAsString(map);
//		} catch(Exception ex) {
//			ex.printStackTrace();
//		}
//		return jsonStr;
	}

	/**
	 * 7,2,8,11,1
	 * @param list
	 * @param title
	 * @return
	 */
	public String formatAdjudgmentWordJson2(List<AdjudgmentWord> list, String title){
		String jsonStr = "";
		String jsonStart = "{\"meta\":{\"name\":\"cp\",\"author\":\"\",\"version\":\"\"},\"format\":\"node_tree\",\"data\":{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\""+title+"\",\"background-color\":\"lightsalmon\",\"foreground-color\":\"white\",\"children\":[";
		String subJson1 = "[{";
		String subJson2 = "[{";
		String subJson7 = "[{";
		String subJson8 = "[{";
		String subJson11 = "[{";

		for(AdjudgmentWord adjudgmentWord : list) {
			if(adjudgmentWord.getClassRelation().getId() == 1){
				subJson1 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 2){
				subJson2 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 7){
				subJson7 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 8){
				subJson8 += addChildrenStart(adjudgmentWord);
			}
			if(adjudgmentWord.getClassRelation().getId() == 11){
				subJson11 += addChildrenStart(adjudgmentWord);
			}
		}
		for(AdjudgmentWord adjudgmentWord : list) {
			if(adjudgmentWord.getClassRelation().getId() == 1){
				subJson1 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 2){
				subJson2 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 7){
				subJson7 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 8){
				subJson8 += "}]";
			}
			if(adjudgmentWord.getClassRelation().getId() == 11){
				subJson11 += "}]";
			}
		}

		if(subJson1.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson1 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"一、行为主体\",\"children\":"+ subJson1 + "}]}";
		}else {
			subJson1 = "";
		}

		if(subJson2.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson2 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"二、行为对象\",\"children\":"+ subJson2 + "}]}";
		}else {
			subJson2 = "";
		}
		if(subJson7.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson7 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"四、行为时空\",\"children\":"+ subJson7 + "}]}";
		}else {
			subJson7 = "";
		}
		if(subJson8.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson8 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"五、行为工具\",\"children\":"+ subJson8 + "}]}";
		}else {
			subJson8 = "";
		}

		if(subJson11.replaceAll("[\\[\\{\\}\\]]", "").length()!=0) {
			subJson11 = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"七、主观心态\",\"children\":[{\"id\":\""+UUID.randomUUID().toString()+"\",\"topic\":\"B目的与动机\",\"children\":"+ subJson11 + "}]}]}";
		} else {
			subJson11 = "";
		}

		jsonStr = jsonStart + subJson1 + subJson2 + subJson7 + subJson8 + subJson11;
		jsonStr = jsonStr.replace("{}", "").replace("}{", "},{");
		return jsonStr + "]}}";
	}


	public String formatSampleJson(Integer convictionId) {
		String jsonStr = config.sampleEntryJson;
		try {
			//行为内容
			List<AdjudgmentWord> list3 = adjudgmentWordService.getByConvictionIdAndClassRelationId(convictionId, 3);

			jsonStr = jsonStr.replace("[{3333}]", addSampleChildren(list3));
			//行为工具
			List<AdjudgmentWord> list8 = adjudgmentWordService.getByConvictionIdAndClassRelationId(convictionId, 8);

			jsonStr = jsonStr.replace("[{8888}]", addSampleChildren(list8));
			//方式方法手段
			List<AdjudgmentWord> list5 = adjudgmentWordService.getByConvictionIdAndClassRelationId(convictionId, 5);

			jsonStr = jsonStr.replace("[{5555}]", addSampleChildren(list5));
			//行为对象=
			List<AdjudgmentWord> list2 = adjudgmentWordService.getByConvictionIdAndClassRelationId(convictionId, 2);
			jsonStr = jsonStr.replace("[{2222}]",addSampleChildren(list2));
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		return jsonStr;
	}

	private String addSampleChildren(List<AdjudgmentWord> list) {
		String str = "[{";
		for(AdjudgmentWord adjudgmentWord : list) {
			str += addChildrenStart(adjudgmentWord);
		}
		for(AdjudgmentWord adjudgmentWord : list){
			str += "}]";
		}
		str += "}]";
		str = str.replace("[{}]", "[]");
		return str;
	}

	private String addChildrenStart(AdjudgmentWord adjudgmentWord){
		String str = "";
		str += "\"id\":\""+UUID.randomUUID().toString()+"\",";
		str += "\"topic\":\""+adjudgmentWord.getContent()+"\",";
		str += "\"children\":[{";
		return str;
	}

	private String addChildrenStart(String topic){
		String str = "";
		str += "\"id\":\""+UUID.randomUUID().toString()+"\",";
		str += "\"topic\":\""+topic+"\",";
		str += "\"children\":[{";
		return str;
	}

}
